<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('equipment.company')" prop="name">
        <el-input
            v-model="queryParams.name"
            :placeholder="$t('equipment.companyInput')"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('program.status')" prop="status">
        <el-select v-model="queryParams.status" :placeholder="$t('mechanism.status')" clearable size="small">
          <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
        >{{ $t('elButton.search') }}
        </el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">{{ $t('elButton.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPerm="['dept_add']"
            class="filter-item"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >{{ $t('elButton.add') }}
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" :content="$t('elButton.refresh')" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery"/>
        </el-tooltip>
        <el-tooltip class="item" effect="dark"
                    :content="showSearch ? $t('elButton.hideSearch') : $t('elButton.showSearch')" placement="top"
        >
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch"/>
        </el-tooltip>
      </div>
    </el-row>

    <el-table
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" :label="$t('equipment.company')" width="260"/>
      <el-table-column prop="code" :label="$t('mechanism.number')" width="260"/>
      <el-table-column prop="sort" :label="$t('mechanism.sort')" width="200"/>
      <el-table-column prop="status" :label="$t('program.status')" :formatter="statusFormat" width="100"/>
      <el-table-column :label="$t('elButton.establishTime')" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.control')" align="center" class-name="small-padding fixed-width"
                       width="180" fixed="right"
      >
        <template slot-scope="scope">
          <el-button
              v-hasPerm="['dept_edit']"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
          >{{ $t('elButton.change') }}
          </el-button>
          <el-button
              v-hasPerm="['dept_add']"
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAdd(scope.row)"
          >{{ $t('elButton.add') }}
          </el-button>
          <el-button
              v-if="scope.row.parentId != 0"
              v-hasPerm="['dept_del']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.row)"
          >{{ $t('elButton.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改机构对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" :modal-append-to-body="true" :append-to-body="true"
               :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col v-if="form.parentId !== 0" :span="24">
            <el-form-item :label="$t('mechanism.superiorOrganization')" prop="parentId">
              <treeselect @input="inputSelect" v-model="form.parentId" :options="deptOptions" :normalizer="normalizer"
                          :placeholder="$t('mechanism.superiorOrganizationSelect')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('equipment.company')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('equipment.companyInput')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('mechanism.number')" prop="code">
              <el-input v-model="form.code" :placeholder="$t('mechanism.numberInput')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('mechanism.contacts')" prop="contacts">
              <el-input v-model="form.contacts" :placeholder="$t('mechanism.contactsInput')" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('mechanism.phone')">
              <el-input v-model="form.phone" :placeholder="$t('mechanism.phoneInput')" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('mechanism.showSort')" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('mechanism.mailbox')" prop="email">
              <el-input v-model="form.email" :placeholder="$t('mechanism.mailboxInput')" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('program.status')">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('submitText') }}</el-button>
        <el-button @click="cancel">{{ $t('cancelText') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, editDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Dept',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      // 机构树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: this.$t('mechanism.superiorOrganizationEmpty'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.$t('equipment.companyEmpty'), trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('mechanism.numberEmpty'), trigger: 'blur' }
        ],
        sort: [
          { required: true, message: this.$t('mechanism.orderSortEmpty'), trigger: 'change' }
        ],
        email: [
          {
            type: 'email',
            message: this.$t('profile.emailRight'),
            trigger: ['blur', 'change']
          }
        ],
        // phone: [
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: this.$t('profile.phoneRight'),
        //     trigger: 'blur'
        //   }
        // ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('status').then(response => {
      this.statusOptions = response.data
    })
    if (this.$route.params.handleAdd) {
      this.handleAdd()
    }
  },
  methods: {
    inputSelect() {
      this.$refs.form.validateField('parentId')
    },
    /** 查询机构列表 */
    getList() {
      this.loading = true
      listDept(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, 'deptId')
        this.loading = false
      })
    },
    /** 转换机构数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.name,
        children: node.children
      }
    },
    /** 查询机构下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        name: undefined,
        code: undefined,
        sort: undefined,
        contacts: undefined,
        phone: undefined,
        email: undefined,
        status: '0'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row !== undefined) {
        this.form.parentId = row.deptId
      }
      this.open = true
      this.title = this.$t('profile.addDept')
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset()
      this.getTreeselect()
      getDept(row.deptId).then(response => {
        this.form = response.data
        this.open = true
        this.title = this.$t('profile.changeDept')
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.deptId !== undefined) {
            editDept(this.form).then(response => {
              console.log(JSON.stringify(response))
              if (response.code === 0) {
                this.msgSuccess(this.$t('loginLog.changeSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addDept(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('addSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDel(row) {
      this.$confirm(this.$t('enterDeleteName') + row.name + this.$t('equipment.deleteEquipment2'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return delDept(row.deptId)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('deleteSuccess'))
      }).catch(function() {
      })
    }
  }
}
</script>
